<?php

App::uses('CrawlUtility', 'Utility');

class EditorStylesController extends AppController{
	
	var $name = 'EditorStyles';
	
	public function admin_add() {
		if( !empty($this->data) && !empty($_POST) ) {
	        $url = $this->data['EditorStyle']['coverimg'];
	        if(strpos($url,'https://mmbiz.qlogo.cn/') !== false || strpos($url,'mmbiz.qpic.cn/') !== false || strpos($url,'mmsns.qpic.cn/') !== false) {
	            $this->_saveImage($url);
	            $this->data['EditorStyle']['coverimg'] = 'http://image2.135editor.com/cache/remote/'.base64_encode($url);
	        }
	         
	        $html = $this->data['EditorStyle']['content'];
	        
	        $html = str_replace('imgproxy.135editor.com','cdn.135editor.com',$html);
	        //$html = str_replace('image.135editor.com','image2.135editor.com',$html);
            $html = str_replace('https://mmbiz.qpic.cn','https://mmbiz.qlogo.cn',$html);
	        $html = str_replace('http://mmbiz.qpic.cn','https://mmbiz.qlogo.cn',$html);
	        
	        $html = preg_replace_callback('~["|\'|\(](https://mmbiz\.qlogo\.cn/[^"\'\)]+?)["|\'|\)]~i',function($matches){
	            $this->_saveImage($matches[1]);
	            $url = 'http://image2.135editor.com/cache/remote/'.base64_encode($matches[1]);
	            return str_replace($matches[1],$url,$matches[0]);
	        },$html);
                 
            $html = preg_replace_callback('~&quot;(https://mmbiz\.qlogo\.cn/[^"\'\)]+?)&quot;~i',function($matches){
                //print_r($matches);
                $this->_saveImage($matches[1]);
                $url = 'http://image2.135editor.com/cache/remote/'.base64_encode($matches[1]);
                return str_replace($matches[1],$url,$matches[0]);
            },$html);
    
            $this->data['EditorStyle']['content'] = $html;
	    }
		parent::admin_add();
	}
	
	public function admin_refresh_img(){
	    return false;
	    
	    if(!empty($_POST)) {
	        $imgs = explode("\r\n",trim($_POST['images']));
	        foreach($imgs as $url) {
	            if(strpos($url,'http://image2.135editor.com/cache/remote/') !== false) {
	                $be = str_replace('http://image2.135editor.com/cache/remote/', '', $url);
	                $url = base64_decode($be);
	                $this->_saveImage($url,true);
	                
	                echo '<br/><img src="http://wx135.oss-cn-hangzhou.aliyuncs.com/cache/remote/'.$be.'">';
	            }
	            elseif(strpos($url,'https://mmbiz.qlogo.cn/') !== false) {
	                $this->_saveImage($url,true);
	            }
	        }
	    }
	}
	
	public function admin_edit($id='',$copy = NULL) {
	    
	    if( !empty($this->data) && !empty($_POST) ) {
	        $url = $this->data['EditorStyle']['coverimg'];
	        if( strpos($url,'https://mmbiz.qlogo.cn/') !== false || strpos($url,'mmbiz.qpic.cn/') !== false || strpos($url,'mmsns.qpic.cn/') !== false ) {
	            $this->_saveImage($url);
	            $this->data['EditorStyle']['coverimg'] = 'http://image2.135editor.com/cache/remote/'.base64_encode($url);
	        }
	         
	        $html = $this->data['EditorStyle']['content'];
	        
	        $html = str_replace('imgproxy.135editor.com','cdn.135editor.com',$html);
	        //$html = str_replace('image.135editor.com','image2.135editor.com',$html);
	        $html = str_replace('http://mmbiz.qpic.cn','https://mmbiz.qlogo.cn',$html);
            $html = str_replace('https://mmbiz.qpic.cn','https://mmbiz.qlogo.cn',$html);
	        
	        $html = preg_replace_callback('~["|\'|\(](https://mmbiz\.qlogo\.cn/[^"\'\)]+?)["|\'|\)]~i',function($matches){
	            $this->_saveImage($matches[1]);
	            $url = 'http://image2.135editor.com/cache/remote/'.base64_encode($matches[1]);
	            return str_replace($matches[1],$url,$matches[0]);
	        },$html);

            $html = preg_replace_callback('~&quot;(https://mmbiz\.qlogo\.cn/[^"\'\)]+?)&quot;~i',function($matches){
                //print_r($matches);
                $this->_saveImage($matches[1]);
                $url = 'http://image2.135editor.com/cache/remote/'.base64_encode($matches[1]);
                return str_replace($matches[1],$url,$matches[0]);
            },$html);
    
            $this->data['EditorStyle']['content'] = $html;
	    }
		parent::admin_edit($id,$copy);
	}
	
	private function _saveImage($url,$force = false) {
		
		return false;
	    
	    $object_name = '/cache/remote/'.base64_encode($url);
	    $exists = CrawlUtility::aliOssExists($object_name,'wx135');
	    if( !$exists || $force ) {
	        $content = CrawlUtility::getRomoteUrlContent($url,array('header'=>array('Referer'=>'http://mp.weixin.qq.com/')),$header);
	        if($content) {
	        	CrawlUtility::saveToAliOss( $content, $object_name,true,true,$header['Content-Type'],array( 'bucket_name' => 'wx135' ) );
	        	// 阿里云与七牛同时保存。remote.wx135.com暂时是直接获取的阿里云oss的内容
	        	$file_path = TMP.random_str(16).'.jpg';
	        	$img_file = new File($file_path, true,0777);
	        	$ret = $img_file->write($content,'w',true);
	        	$img_file->close();
	        	if(file_exists($file_path)) {
	        		$ret = CrawlUtility::saveToQiniu($file_path, $object_name);
	        		@unlink($file_path);
	        		return $ret;
	        	}
	        	else{
	        		return false;
	        	}
	        }
	    }
	    return true;
	}

	public function admin_saveEmotion(){
	    $file = ROOT.DS.WEBROOT_DIR.'/js/ueditor/dialogs/emotion/emotion-o.html';

        $html = file_get_contents($file);
        $html = preg_replace_callback('~["|\'|\(](http://[^"\'\)]+?/cache/remote/[^"\'\)]+?)["|\'|\)]~i',function($matches){
            $save_path = ROOT.DS.WEBROOT_DIR.'/js/ueditor/dialogs/emotion/images/';
            $code = $this->_offlineImage($matches[1],$save_path);
            if($code){
                return str_replace($matches[1],'./images/'.$code,$matches[0]);
            }
            else{
                return $matches[0];
            }
        },$html);
        $html = preg_replace_callback('~src="(http://[^"\'\)]+?)"~i',function($matches){
            $save_path = ROOT.DS.WEBROOT_DIR.'/js/ueditor/dialogs/emotion/images/';
            $code = $this->_offlineImage($matches[1],$save_path);
            if($code){
                return str_replace($matches[1],'./images/'.$code,$matches[0]);
            }
            else{
                return $matches[0];
            }
        },$html);
        $html = preg_replace_callback('~\'(http://[^"\'\)]+?)\'~i',function($matches){
            $save_path = ROOT.DS.WEBROOT_DIR.'/js/ueditor/dialogs/emotion/images/';
            $code = $this->_offlineImage($matches[1],$save_path);
            if($code){
                return str_replace($matches[1],'./images/'.$code,$matches[0]);
            }
            else{
                return $matches[0];
            }
        },$html);

        $newfile = ROOT.DS.WEBROOT_DIR.'/js/ueditor/dialogs/emotion/emotion-n.html';
        file_put_contents($newfile,$html);
        exit;
    }

    private function _offlineImage($url,$path='') {

        $urlinfo = parse_url($url);
        $ext = 'jpg';
        if( substr($urlinfo['path'],0,14) == '/cache/remote/' ) {
            $base64 =  substr($urlinfo['path'],14);
            @list($base64,$rule) = explode('@',$base64);
            $code = $base64;
            $srcurl = base64_decode($base64);
            if(strpos($srcurl,'mmbiz_png') !== false || strpos($srcurl,'wx_fmt=png') !== false) {
                $ext = 'png';
            }
            elseif(strpos($srcurl,'mmbiz_gif') !== false || strpos($srcurl,'wx_fmt=gif') !== false) {
                $ext = 'gif';
            }
            elseif(strpos($srcurl,'mmbiz_jpg') !== false || strpos($srcurl,'wx_fmt=jpeg') !== false) {
                $ext = 'jpg';
            }
        }
        else{
            $fext =  strtolower( end( explode('.',$urlinfo['path']) ) );
            if( in_array($fext,array('png','jpg','jpeg','gif')) ) {
                $ext = $fext;
            }
            $srcurl = $url;

        }
        $code = md5($srcurl).'.'.$ext;
        if(empty($path)) {
            //$code = str_replace('/','%2F',$code);
            $object_name = DATA_PATH.'offline'.DS.'cache'.DS.'remote'.DS.$code;
            $object_name = str_replace('\\','/',$object_name);
        }
        else{
            $object_name = $path.DS.$code;
        }

        if( file_exists($object_name) ){
            return $code;
        }
        echo "\nget $srcurl<br/>\n" ;

        $content = CrawlUtility::getRomoteUrlContent($url,array(),$header);
        if($content) {
            if (!$handle = fopen($object_name, 'wb')) {
                echo "\ncannot open $object_name\n";
                return false;
            }
            // 将$somecontent写入到我们打开的文件中。
            if (fwrite($handle, $content) === FALSE) {
                echo "\ncannot save $object_name\n";
                return false;
            }
            fclose($handle);
            return $code;
        }
        else{
            echo "\n$srcurl, get error.\n";
            return false;
        }

    }

	public function admin_saveTplImage($name = 'styles') {

	    $file = DATA_PATH.'/offline/'.$name.'.html';
	    $html = file_get_contents($file);

        $html = preg_replace_callback('~["|\'|\(](http://[^"\'\)]+?/cache/remote/[^"\'\)]+?)["|\'|\)]~i',function($matches){
            $code = $this->_offlineImage($matches[1]);
            if($code){
                return str_replace($matches[1],'./cache/remote/'.$code,$matches[0]);
            }
            else{
                return $matches[0];
            }
        },$html);
        $html = preg_replace_callback('~&quot;(http://[^"\'\)]+?/cache/remote/[^"\'\)]+?)&quot;~i',function($matches){
            $code = $this->_offlineImage($matches[1]);
            if($code){
                return str_replace($matches[1],'./cache/remote/'.$code,$matches[0]);
            }
            else{
                return $matches[0];
            }
        },$html);

        $html = preg_replace_callback('~["|\'|\(](http://(image|rdn|qdn|static).(135editor|wx135).com/[^"\'\)]+?)["|\'|\)]~i',function($matches){
            $code = $this->_offlineImage($matches[1]);
            if($code){
                return str_replace($matches[1],'./cache/remote/'.$code,$matches[0]);
            }
            else{
                return $matches[0];
            }
        },$html);
        $html = preg_replace_callback('~&quot;(http://.+?/[^"\'\)]+?)&quot;~i',function($matches){
            $code = $this->_offlineImage($matches[1]);
            if($code){
                return str_replace($matches[1],'./cache/remote/'.$code,$matches[0]);
            }
            else{
                return $matches[0];
            }
        },$html);

        $html = preg_replace_callback('~url\((http://.+?/[^"\'\)]+?)\)~i',function($matches){
            $code = $this->_offlineImage($matches[1]);
            if($code){
                return str_replace($matches[1],'./cache/remote/'.$code,$matches[0]);
            }
            else{
                return $matches[0];
            }
        },$html);

        $html = preg_replace_callback('~src="(http://.+?/[^"\'\)]+?)"~i',function($matches){
            $code = $this->_offlineImage($matches[1]);
            if($code){
                return str_replace($matches[1],'./cache/remote/'.$code,$matches[0]);
            }
            else{
                return $matches[0];
            }
        },$html);

        /*
        $html = preg_replace_callback('~["|\'|\(](http://remote\.wx135\.com/[^"\'\)]+?)["|\'|\)]~i',function($matches){
            //print_r($matches);
            $url = $matches[1];
            $urlinfo = parse_url($url);
            parse_str($urlinfo['query'],$query);
            $wxurl =  $query['d'];
            $this->_saveImage($wxurl);
            $url = 'http://image2.135editor.com/cache/remote/'.base64_encode($wxurl);
            return str_replace($matches[1],$url,$matches[0]);
        },$html);

        $html = preg_replace_callback('~&quot;(https://mmbiz\.qlogo\.cn/[^"\'\)]+?)&quot;~i',function($matches){
            //print_r($matches);
            $this->_saveImage($matches[1]);
            $url = 'http://image2.135editor.com/cache/remote/'.base64_encode($matches[1]);
            return str_replace($matches[1],$url,$matches[0]);
        },$html);*/
        $file = DATA_PATH.'/offline/'.$name.'_new.html';
        file_put_contents($file,$html);
        exit;
    }
	
	public function admin_previewCoverImg($modelClass='EditorStyle') {
	    $this->loadModel($modelClass);
	    $page = $_GET['page'] ? $_GET['page'] : 1;
	    $datalist = $this->{$modelClass}->find('all',array(
	        'conditions'=> array(
	            'coverimg like' => '%mmbiz.qlogo.cn%',
	        ),
	        'limit'=> 50,
	        'page' => $page,
	        'order' => 'id asc',
	    ));
	    header('Content-Type:text/html; charset=UTF-8');
	    foreach($datalist as $item) {
	        $url = $item[$modelClass]['coverimg'];
	        if(strpos($url,'https://mmbiz.qlogo.cn/') !== false) {
	            $this->_saveImage($url);
	            $newurl = 'http://image2.135editor.com/cache/remote/'.base64_encode($url);
	
	            echo '<p>ID:'.$item[$modelClass]['id'].'</p><div style="margin:10px auto;width:820px;word-break: break-all;">
	                   <div style="margin:10px 0;width:400px;float:left;">'.$url.'<img src="'.$url.'" style="max-width:100%"></div>
	                   <div style="margin:10px 0;width:400px;float:right;">'.$newurl.'<img src="'.$newurl.'" style="max-width:100%"></div>
	                   <p style="clear:both;"></p>
	              </div>';
	
	            if($_REQUEST['replace'] ) {
	                $this->{$modelClass}->updateAll(array('coverimg'=> $this->{$modelClass}->escape_string($newurl) ),
	                    array('id'=> $item[$modelClass]['id']));
	            }
	        }
	    }
	    echo "over";
	    exit;
	}
	
	public function admin_previewImg() {	    
	    $page = $_GET['page'] ? $_GET['page'] : 1;	    
	    $datalist = $this->EditorStyle->find('all',array(
	        'conditions'=> array(
	           'content like' => '%mmbiz.qlogo.cn%',
	         ),
	        'limit'=> 50,
	        'page' => $page,
	        'order' => 'id asc',	        
	    ));
	    header('Content-Type:text/html; charset=UTF-8');
	    foreach($datalist as $style) {
	        $html = $style['EditorStyle']['content'];
	        
	        $html = str_replace('imgproxy.135editor.com','cdn.135editor.com',$html);
	        $html = str_replace('image.135editor.com','image2.135editor.com',$html);
	        
	        $html = preg_replace_callback('~["|\'|\(](https://mmbiz\.qlogo\.cn/[^"\'\)]+?)["|\'|\)]~i',function($matches){
	            $this->_saveImage($matches[1]);
	            $url = 'http://image2.135editor.com/cache/remote/'.base64_encode($matches[1]);
	            return str_replace($matches[1],$url,$matches[0]);
	        },$html);
	        
            $html = preg_replace_callback('~["|\'|\(](http://remote\.wx135\.com/[^"\'\)]+?)["|\'|\)]~i',function($matches){
                //print_r($matches);
                $url = $matches[1];
                $urlinfo = parse_url($url);
                parse_str($urlinfo['query'],$query);
                $wxurl =  $query['d'];
                $this->_saveImage($wxurl);
                $url = 'http://image2.135editor.com/cache/remote/'.base64_encode($wxurl);
                return str_replace($matches[1],$url,$matches[0]);
            },$html);
            
	        $html = preg_replace_callback('~&quot;(https://mmbiz\.qlogo\.cn/[^"\'\)]+?)&quot;~i',function($matches){
	            //print_r($matches);
	            $this->_saveImage($matches[1]);
	            $url = 'http://image2.135editor.com/cache/remote/'.base64_encode($matches[1]);
	            return str_replace($matches[1],$url,$matches[0]);
	        },$html);
	        
	        echo '<br><hr><hr><p>ID:'.$style['EditorStyle']['id'].'</p><div style="margin:10px auto;width:820px;"><div style="margin:10px 0;width:400px;float:left;">'.$style['EditorStyle']['content'].'</div><div style="margin:10px 0;float:right;width:400px;">'; echo $html; echo '</div><p style="clear:both;"></p></div><br><hr><hr>';
	    }
	    exit;
	}
	
	public function admin_replaceImg() {
	     
	   $page = $_GET['page'] ? $_GET['page'] : 1;	    
	    $datalist = $this->EditorStyle->find('all',array(
	        'conditions'=> array(
	           'content like' => '%mmbiz.qlogo.cn%',
	         ),
	        'limit'=> 50,
	        'page' => $page,
	        'order' => 'id asc',	        
	    ));
	    header('Content-Type:text/html; charset=UTF-8');
	    foreach($datalist as $style) {
	        $html = $style['EditorStyle']['content'];

	        $html = str_replace('imgproxy.135editor.com','cdn.135editor.com',$html);
	        $html = str_replace('image.135editor.com','image2.135editor.com',$html);
	        
	        $html = preg_replace_callback('~["|\'|\(](https://mmbiz\.qlogo\.cn/[^"\'\)]+?)["|\'|\)]~i',function($matches){
	            $url = 'http://image2.135editor.com/cache/remote/'.base64_encode($matches[1]);
	            return str_replace($matches[1],$url,$matches[0]);
	        },$html);
	        
            $html = preg_replace_callback('~["|\'|\(](http://remote\.wx135\.com/[^"\'\)]+?)["|\'|\)]~i',function($matches){
                //print_r($matches);
                $url = $matches[1];
                $urlinfo = parse_url($url);
                parse_str($urlinfo['query'],$query);
                $wxurl =  $query['d'];
                $url = 'http://image2.135editor.com/cache/remote/'.base64_encode($wxurl);
                return str_replace($matches[1],$url,$matches[0]);
            },$html);
            
	        $html = preg_replace_callback('~&quot;(https://mmbiz\.qlogo\.cn/[^"\'\)]+?)&quot;~i',function($matches){
	            //print_r($matches);
	            $url = 'http://image2.135editor.com/cache/remote/'.base64_encode($matches[1]);
	            return str_replace($matches[1],$url,$matches[0]);
	        },$html);
	        
	        $this->EditorStyle->updateAll(array('content'=> $this->EditorStyle->escape_string($html) ),
	            array('id'=> $style['EditorStyle']['id']));
	        //echo '<br><hr><hr><div style="margin:10px auto;width:820px;"><div style="margin:10px 0;width:400px;float:left;">'.$style['EditorStyle']['content'].'</div><div style="margin:10px 0;float:right;width:400px;">'; echo $html; echo '</div><p style="clear:both;"></p></div><br><hr><hr>';
	    }	    
	    echo 'done over';
	    exit;
	}
	
	private function save_coverimg($content,$id) {
		
		$width = 320; $height = 480;
		$html = '<!DOCTYPE html><html lang="en"><head>
<meta charset="utf-8">
<meta content="text/html; charset=utf-8" http-equiv="content-type" />
<style>
body
{
	/* Remove the background color to make it transparent */
	margin: 10px;
	overflow:hidden;
	max-height:10000px;
	font-family: "Helvetica Neue",Helvetica,"Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;
	background:#FFF;
}
* {max-width: 100%!important;margin:0;padding:0;font-style:normal;box-sizing: border-box!important;-webkit-box-sizing: border-box!important;word-wrap: break-word!important;}
p{clear:both;margin:0 0;}
		
blockquote{margin:0;padding-left:10px;border-left:3px solid #DBDBDB;}
		
ol,ul,dl
{
	margin: 0px 0px;
	/* preserved spaces for list items with text direction other than the list. (#6249,#8049)*/
	padding: 0 40px;
}
</style>
						</head><body style="width:'.$width.';max-height:10000px;">'.$content.'</body></html>';
		$uuid = 'template_'.$id;
		$tmp_file = TMP.$uuid.'.html';
		$img_file = TMP.$uuid.'.jpg';
		file_put_contents($tmp_file, $html);
		$retval = array();
		$cmd = "wkhtmltoimage --disable-smart-width --width $width --height $height ".($tmp_file)." ".$img_file;
		$ret =system($cmd,$retval);
		
		// 缩放处理图片,替换原图(压缩)
		App::uses('ImageResize','Lib');
		$image = new ImageResize();
		$image->resizefile($img_file,$img_file,$width,$height);
		
		CrawlUtility::saveToAliOss($img_file, '/135editor/tpl_covors/'.$id.'.jpg');
		
	}
	
}